define([
  'jquery',
  'jqueryui',
  'underscore',
  'backbone',
  'dateformatter',
  'models/search/HistoryModel',
  'text!templates/search/historyTemplate.html',
  'views/search/HistoryResultsView',
  'msgbox',
], function($,ui, _, Backbone, Dateformatter, HistoryModel, historyTemplate,HistoryResultsView,MsgBox){

  var SearchView = Backbone.View.extend({
    el: $(".mainpanel"),
    model: new HistoryModel(),
    events: {'click #SearchHistory' : 'submitSearch'
    	
    	/*,
        "change #historyForm :input" :"changedHistoryForm"*//*,
        "autocompleteselect": "changedSearchAC"*/} ,
    initialize: function(){
//    	_.bindAll("#searchForm :input", "changedSearchForm");
    },
    render: function(){
       	var data = {
      		  search: this.model,
      	        _: _ 
      	      };
      	var self=this;
  	      var compiledTemplate = _.template( historyTemplate, data );
  	      this.$el.html(compiledTemplate);
	      $("input#patientName").autocomplete({    	    
	    	  source: function(request,response){
	    			 $.ajax({
	    			        type: "GET",
	    			        url: "/getPatientDetails?name="+$("#patientName").val()+"&clientId="+$("#clientId").val(),
	    			        success: function(data){
	    			              response($.map(data, function(item) {
	    			                    return { 
	    			                        label: item.name + " - "+ item.provider ,
	    			                        value: item.name,
	    			                        id: item.id,
	    			                        userid: item.userid,
	    			                        provider: item.provider
	    			                        };
	    			                    }));
	    			        }
	    		    });
	    	    },
	    	    minLength: 3,
	    	    select: function(e,ui){
	    	    	self.changedHistoryAC("patientName",ui);
	    	    	ui.item.provider=="google"? $(".doctorimage").html("<img class=\"s-img\" src=\"https://profiles.google.com/s2/photos/profile/"+ui.item.userid+"\">"):
	    	    		(ui.item.provider=="facebook"? $(".doctorimage").html("<img class=\"s-img\" src=\"https://graph.facebook.com/"+ui.item.userid+"/picture\">"):
	    	    			(ui.item.provider=="twitter"? $(".doctorimage").html("<img class=\"s-img\" src=\"https://api.twitter.com/1/users/profile_image?user_id="+ui.item.userid+"\">"):"")
	    	    			);
	    	    	
	    	    }
	    	});
	      $("input#clientId").autocomplete({    	    
	    	  source: function(request,response){
 			 $.ajax({
 			        type: "GET",
 			        url: "/getPatientDetails?name="+$("#patientName").val()+"&clientId="+$("#clientId").val(),
 			        success: function(data){
 			              response($.map(data, function(item) {
 			                    return { 
 			                        label: item.clientId,
 			                        value: item.clientId,
			                        id: item.id,
			                        userid: item.userid,
			                        provider: item.provider
 			                        };
 			                    }));
 			        }
 		    });
 	    },
 	    minLength: 3,
 	    select: function(e,ui){
 	    	
 	    	self.changedHistoryAC("clientId",ui);
	    	ui.item.provider=="google"? $(".doctorimage").html("<img class=\"s-img\" src=\"https://profiles.google.com/s2/photos/profile/"+ui.item.userid+"\">"):
	    		(ui.item.provider=="facebook"? $(".doctorimage").html("<img class=\"s-img\" src=\"https://graph.facebook.com/"+ui.item.userid+"/picture\">"):
	    			(ui.item.provider=="twitter"? $(".doctorimage").html("<img class=\"s-img\" src=\"https://api.twitter.com/1/users/profile_image?user_id="+ui.item.userid+"\">"):"")
	    			);
 	    }
 	});
    },
    close: function(){
    	
    },
    submitSearch: function(){
    	console.log(this.model.toJSON());
       	if($.isEmptyObject(this.model.toJSON())){
     		 $.msgBox({
				    title:"Appment",
				    content:"Please fill-in at least 1 search criteria",
				    type:"error"
				});

       	}else{
    		var id;
        	_.each(this.model.toJSON(), function(value, key) {
        	    if(key =="id")
        	    	id=value;
        	  }); 
        	var self=this;
	   		 $.ajax({
			        type: "POST",
			        url: "/getHistoryResults/"+id,
			        success: function(data){
			        	console.log(data);
			        	self.model.set("historyresults",data);
			        	//data = _(data).flatten(true);
			        	self.goTo("historyresults");
			        }
		    });

//    		this.model.fetch({data: JSON.stringify(this.model)});	
    	
       	}
    },
    changedHistoryAC: function ( e, ui ) {
        var value = $("#"+e).val();
        var obj = "{\""+e +"\":\""+ui.item.value+"\",\"id\":"+ui.item.id+"}";
        var objInst = JSON.parse(obj);
        this.model.set(objInst);
    	
  
    },
    changedHistoryForm:function(evt) {
       var changed = evt.currentTarget;
       var value = $("#"+changed.id).val();
       var obj = "{\""+changed.id +"\":\""+value+"\"}";
       var objInst = JSON.parse(obj);
       this.model.set(objInst);
    }
  });

  return SearchView;
});
